package queuedemo;

//使用双向链表实现队列
public class MyQueue {
    static class ListNode {
        public int val;
        public ListNode next;
        public ListNode prev;

        public ListNode(int val) {
            this.val = val;
        }
    }

    public ListNode first;//队头
    public ListNode last;//队尾
    public int usedSize;

    //尾插法，入队
    public void offer(int val) {
        ListNode node = new ListNode(val);

        if (first == null) {
            first = last = node;
            return;
        }

        last.next = node;
        node.prev = last;
        last = node;

        usedSize++;
    }

    //删除头节点，出队
    public int poll() {
        if (first == null) {
            return -1;
        }

        int oldVal = first.val;

        first = first.next;

        if (first == null) {
            last = null;
        } else {
            first.prev = null;
        }

        usedSize--;

        return oldVal;
    }

    public int peek() {
        if (first == null) {
            return -1;
        }

        return first.val;
    }

    public int size() {
        return usedSize;
    }

    public boolean isEmpty() {
        return usedSize == 0;
    }
}
